package com.znjc.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.constant.DeviceConstants;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysDept;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.StringUtils;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.DevicePoint;
import com.znjc.device.domain.DeviceType;
import com.znjc.device.service.IDevicePointService;
import com.znjc.device.service.IDeviceRuleRefService;
import com.znjc.device.service.IDeviceTypeService;
import com.znjc.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【测点】Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@RestController
@RequestMapping("/device/point")
public class DevicePointController extends BaseController {
    @Autowired
    private IDevicePointService devicePointService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IDeviceRuleRefService deviceRuleRefService;
    @Autowired
    private IDeviceTypeService deviceTypeService;
    /**
     * 查询测点管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:point:list')")
    @GetMapping("/list")
    public TableDataInfo list(DevicePoint devicePoint) {
        startPage();
        LambdaQueryWrapper<DevicePoint> wrapper = getWrapper(devicePoint);
        List<DevicePoint> list = devicePointService.list(wrapper);
        return getDataTable(packList(list));
    }

    /**
     * 导出测点管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:point:export')")
    @Log(title = "测点管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DevicePoint devicePoint) {
        LambdaQueryWrapper<DevicePoint> wrapper = getWrapper(devicePoint);
        List<DevicePoint> list = devicePointService.list(wrapper);
        ExcelUtil<DevicePoint> util = new ExcelUtil<DevicePoint>(DevicePoint.class);
        util.exportExcel(response, packList(list), "测点管理数据");
    }

    /**
     * 获取测点管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:point:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DevicePoint point = devicePointService.getById(id);
        if(null != point){
            DeviceType type = deviceTypeService.getById(point.getTypeId());
            if (null != type) {
                point.setTypeName(type.getName());
            }
        }
        return success(point);
    }

    /**
     * 新增测点管理
     */
    @PreAuthorize("@ss.hasPermi('device:point:add')")
    @Log(title = "测点管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DevicePoint devicePoint) {
        return toAjax(devicePointService.save(devicePoint));
    }

    /**
     * 修改测点管理
     */
    @PreAuthorize("@ss.hasPermi('device:point:edit')")
    @Log(title = "测点管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DevicePoint devicePoint) {
        return toAjax(devicePointService.updateById(devicePoint));
    }

    /**
     * 删除测点管理
     */
    @PreAuthorize("@ss.hasPermi('device:point:remove')")
    @Log(title = "测点管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        boolean flag = devicePointService.removeByIds(new ArrayList<>(Arrays.asList(ids)));
        if(flag){
            for(Long id:ids){
                deviceRuleRefService.deleteRefByPointId(id);
            }
        }
        return toAjax(flag);
    }

    /**
     * 获取设备测点选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<DevicePoint> devices = devicePointService.list();
        return success(devices);
    }

    /**
     * 查询公共方法
     *
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(DevicePoint entity) {
        LambdaQueryWrapper<DevicePoint> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (StringUtils.isNotEmpty(entity.getPointName())) {
                wrapper.like(DevicePoint::getPointName, entity.getPointName());
            }
            if (StringUtils.isNotEmpty(entity.getStatus())) {
                wrapper.eq(DevicePoint::getStatus, entity.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 结果封装
     *
     * @param list
     * @return
     */
    private List<DevicePoint> packList(List<DevicePoint> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if(null != entity.getTypeId()){
                    DeviceType type = deviceTypeService.getById(entity.getTypeId());
                    if (null != type) {
                        entity.setTypeName(type.getName());
                    }
                }
                if (null != entity.getDeptId()) {
                    SysDept dept = deptService.selectDeptById(entity.getDeptId());
                    if (null != dept) {
                        entity.setDeptName(dept.getDeptName());
                    }
                }
            });
        }
        return list;
    }
}
